
/*
* @ author: karim daher
* @ date: 04-28-2008
* @version: 0.1
 */

class ContentController {
    AuthenticateService authenticateService
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        if(!params.max) params.max = 10
        [ contentList: Content.list( params ) ]
    }

    def show = {
        def content = Content.get( params.id )

        if(!content) {
            flash.message = "Content not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ content : content ] }
    }

    def delete = {
        def content = Content.get( params.id )
        if(content) {
            content.status = Content.STATUS_DELETED
            flash.message = "Content ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = "Content not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def content = Content.get( params.id )

        if(!content) {
            flash.message = "Content not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ content : content ]
        }
    }

    def update = {
        def content = Content.get( params.id )
        if(content) {
            content.properties = params
            if(!content.hasErrors() && content.save()) {
                flash.message = "Content ${params.id} updated"
                redirect(action:show,id:content.id)
            }
            else {
                render(view:'edit',model:[content:content])
            }
        }
        else {
            flash.message = "Content not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def content = new Content()
        content.properties = params
        return ['content':content]
    }

    def save = {
        def content = new Content(params)
        def user =   Person.findWhere(username:authenticateService?.principal()?.username)
        if(!user?.profile){
            //create profile
            def prof = new MemberProfile()
            prof.save(flush:true)
            user.profile = prof
        }
        content?.createdBy = user
        //content?.member =   user?.profile
        if(!content.hasErrors() && content.save()) {

            if(user){
                user?.profile?.addToBlogs(content)
            }
            flash.message = "Content ${content.id} created"
            redirect(action:show,id:content.id)
        }
        else {
            render(controller:"content",view:'create',model:[content:content])
        }
    }

    def addComment = {
        def comment = new Comment()
        comment.properties = params
        return ['comment':comment, 'contentID':params.id]
    }
}